<%--
   * 【描 述】：字典管理页面
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-08-05
   *  @since          2014-08-05
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>
<html>
  <head>
    <title>字典管理</title>
    <script type="text/javascript">
    	Ext.onReady(function() {
    		Ext.QuickTips.init();
	    	Ext.form.Field.prototype.msgTarget = 'qtip';
	    	
	    	var westStore = new Ext.data.Store({//角色数据源
				proxy: new Ext.data.HttpProxy({
					url: 'DictAction!getDictTypeList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'id'},
		        	{name: 'dictName'},
		        	{name: 'dictCode'},
		        	{name: 'createDate', type: 'date'},
				    {name: 'enableStatus'},
				    {name: 'remark'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: {
					params:{
						start: PAGING_START_INDEX,
						limit: PAGING_PAGE_SIZE
					}
				}
			});
	    	
	    	var centerStore = new Ext.data.Store({//菜单数据源
				proxy: new Ext.data.HttpProxy({
					url: 'DictAction!getDictList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
		        	{name: 'dictLabel'},
				    {name: 'dictValue'}
				])),
				remoteSort: false,
				autoLoad: false
			});
	    	
	    	var westModel = new Ext.grid.CheckboxSelectionModel({
	    		singleSelect: true,//单选
	    		header: '',//空来代替checkbox全选框
		    	listeners: {
	    			rowselect: function(selModel, rowIndex, record) {//行选中
	    				centerStore.baseParams = {
			        		dictTypeId: record.get('id')
	    				};
	    				centerStore.reload({
	    					params: {
	    						start: PAGING_START_INDEX,
								limit: PAGING_PAGE_SIZE
	    					}
	    				});
	    			}
		    	}
		    });
	    	
	    	var westCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true,// 默认全部列可排序
		            align: 'center'
		        },
		        columns: [
		        	westModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50
					}),{
		        		id: 'dictTypeId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						hidden: true
						//sortable: true
					},{
		        		id: 'roleName',
			        	header: '字典名称',
			        	dataIndex: 'dictName',
			      		width: 80
			        },{
		        		id: 'dictCode',
			        	header: '代码',
			        	dataIndex: 'dictCode',
			      		width: 80
			        },{
		        		id: 'remark',
			        	header: '备注',
			        	dataIndex: 'remark',
			      		width: 130,
			      		renderer: function(value, metadata, record, rowIndex, colIndex, store) {
			        		metadata.attr = 'ext:qtip="'+ value +'"';
			        		return value;
			        	}
			        },{
			        	id: 'enableStatus',
			        	header: '状态',
			        	dataIndex: 'enableStatus',
			        	width: 60,
			        	renderer: function(value, cellmeta, record) {
			        		return cf_enableStatus(value);
			        	}
			        }
		        ]
		    });
	    	
	    	var centerModel = new Ext.grid.CheckboxSelectionModel();
	    	var centerCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true, // 默认全部列可排序          
		            align: 'center'
		        },
		        columns: [
		        	centerModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50
					}),{
		        		id: 'dictId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						hidden: true
						//sortable: true
					},{
						id: 'dictTypeId',
						header: '类型Id',
						dataIndex: 'dictTypeId',
						width: 25,
						hidden: true
					},{
		        		id: 'dictLabel',
			        	header: cf_getRequiredItem('标签'),
			        	dataIndex: 'dictLabel',
			      		width: 80,
			      		editor: new Ext.form.TextField({
			      			allowBlank: false,
			      			blankText: '必填项不可为空',
			      			maxLength: 25,
			      			maxLengthText: '标签长度不可大于{0}字符'
			      		})
			        },{
			        	id: 'dictValue',
			        	header: cf_getRequiredItem('数值'),
			        	dataIndex: 'dictValue',
			        	width: 50,
			        	editor: new Ext.form.TextField({
			        		allowBlank: false,
			        		blankText: '必填项不可为空',
			        		maxLength: 6,
			      			maxLengthText: '数值长度不可大于{0}字符'
			        	})
			        }
		        ]
		    });
//==================================================
	    	var viewport = new Ext.Viewport({
	    		layout: 'border',
	    		items:[
	    			new Ext.grid.GridPanel({
			        	region: 'west',//西
			        	id: 'westViewport',
				        autoScroll: true,
					    store: westStore,
					    cm: westCol,
					    sm: westModel,
					    //autoExpandColumn: 'roleName', // column with this id will be expanded
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    //clicksToEdit: 1,
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
					    tbar: [{
					        text: '新增',
					        iconCls: 'addBtn',
					        handler: function() {
					    		dictTypeController('C', this.text);
					        }
					    },{
					        text: '修改',
					        iconCls: 'editBtn',
					        handler: function() {
					    		var grid = Ext.getCmp('westViewport');
					    		var record = grid.getSelectionModel().getSelected();
		        				if(record) {
		        					dictTypeController('U', this.text, record);
				            	} else {
				            		Ext.MessageBox.alert('提示', '请选择一条记录.');
				            	}
					        }
					    },{
					        text: '删除',
					        iconCls: 'deleteBtn',
					        handler: function() {
					    		var grid = Ext.getCmp('westViewport');
					    		var record = grid.getSelectionModel().getSelected();
					    		if(record) {
					    			Ext.MessageBox.confirm('提示', '确认删除?', 
					    				function(btn){
					    					if(btn == BUTTON_YES) {
					    						Ext.Ajax.request({
					    							url: 'DictAction!dictTypeController.do',
					    							method: 'POST',
					    							params: {
					    								'dictType.cudType': 'D',
					    								'dictType.id': record.get('id')
					    							},
					    							success: function(result, request) {
					    								westStore.remove(record);
					    								refresh('west');
					    							},
					    							failure: function(result, request) {
					    								Ext.MessageBox.alert('提示', '操作失败!请重试.');
					    							}
					    						});
					    					}
					    				}
					    			);
					    		} else {
					    			Ext.MessageBox.alert('提示', '请选择一条记录.');
					    		}
					        }
					    },'->','字典名称',
				        	new Ext.form.TwinTriggerField({
							    trigger1Class: 'x-form-clear-trigger',
							    trigger2Class: 'x-form-search-trigger',
							    hideTrigger1: true,
							    autoWidth: true,
							    listeners: {
							        'specialkey': function(f, e){
							        	if(e.getKey() == e.ENTER){
							            	this.onTrigger2Click();
							        	}
							    	}
							 	},
							 	onTrigger1Click:function(){
							    	this.setRawValue('');
							     	this.triggers[0].hide();
							    	return false;
							 	},
							 	onTrigger2Click:function(){
							    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
						        	this.triggers[0].show();
							        westStore.reload({
							        	params: {
							        		start: PAGING_START_INDEX,
											limit: PAGING_PAGE_SIZE,
							        		'dictName': name
							        	}
							    	});
								}
							})
					    ],
					    bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, westStore),
					    viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	},
			        	listeners: {
			        		afterrender: function(grid) {
			        			setTimeout(function(){//渲染速度问题延迟500毫秒
			        				if(westStore.getCount() > 0) {//默认选中首行
				        				grid.getSelectionModel().selectRow(0);
				        			}
			        			}, 500);
			        		}
			        	}
					}),
					new Ext.grid.EditorGridPanel({
						id: 'centerViewport',
				        region: 'center',
				        autoScroll: true,
				        store: centerStore,
					    cm: centerCol,
					    sm: centerModel,
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    //clicksToEdit: 1,
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
			        	tbar: [{
				        		text: '添加',
						        iconCls: 'addBtn',
						        handler : function() {
			        				var RecordSet = Ext.data.Record.create([
							    	   {name: 'cudType'},
							    	   {namd: 'id'},
							    	   {name: 'dictTypeId'},
							    	   {name: 'dictLabel'},
							    	   {name: 'dictValue'}
								    ]);
						    		var record = new RecordSet({
					            		cudType: 'C',
					            		id: '',
					            		dictTypeId: Ext.getCmp('westViewport').getSelectionModel().getSelected().get('id'),
					            		dictLabel:'',
					            		dictValue: ''
					            	});
						    		
						    		var grid = Ext.getCmp('centerViewport');
					            	grid.stopEditing();
									grid.getStore().insert(0, record);
									grid.startEditing(0, 4);
									for(var i = 0; i < grid.getStore().getCount(); i++){ //使RowNumberer加1
										if(Ext.isIE) {
											grid.getView().getCell(i, centerCol.getIndexById('rownum')).firstChild.innerText = i + 1;
										} else {
											grid.getView().getCell(i, centerCol.getIndexById('rownum')).firstChild.textContent = i + 1;
										}
									}
									grid.getSelectionModel().selectFirstRow();
				        		}
				        	},{
				        		text: '删除',
						        iconCls: 'deleteBtn',
						        handler : function() {
				        			var grid = Ext.getCmp('centerViewport');
				        			var records = grid.getSelectionModel().getSelections();
				        			if(records.length > 0) {
				        				for(var i = 0; i < records.length; i ++) {
				        					records[i].set('cudType', 'D');
				        					if(grid.getStore().modified.indexOf(records[i]) == -1)
				        						grid.getStore().modified.push(records[i]);
				        					grid.getStore().remove(records[i]);
				        				}
				        			} else {
				        				Ext.MessageBox.alert('提示', '请选择一条记录');
				        			}
						        }
				        	},{
				        		text: '保存',
				        		iconCls: 'saveBtn',
				        		handler: function() {
				        			var records = centerStore.getModifiedRecords();
				        			if(records.length > 0) {
				        				if(!cf_validateGrid(Ext.getCmp('centerViewport'), centerCol, ['dictLabel','dictValue']))
				        					return;
				        				Ext.MessageBox.confirm('提示', '确认保存?',
				        					function(btn) {
				        						if(btn == BUTTON_YES) {
				        							cf_ShowMessageBox('保存中..');
				        							var data = "[";
				        							for(var i = 0, len = records.length; i < len; i++) {
				        								data = data + "{cudType:'" + records[i].get('cudType') +
										            		"', id:'" + records[i].get('id') + 
										            		"', dictTypeId:'" + records[i].get('dictTypeId') + 
										            		"', dictLabel:'" + records[i].get('dictLabel') + 
										            		"', dictValue:'" + records[i].get('dictValue') + 
										            		"'}";
											            if (i < len - 1) {data = data + ",";}
											        }
													data = data + "]";
			        	
			        								Ext.Ajax.request({
			        									url: 'DictAction!dictController.do',
			        									method: 'POST',
			        									params: {'jsonData': data},
			        									success: function(result, request) {
			        										Ext.MessageBox.alert('提示', '操作成功', 
			        											function(btn) {
			        												refresh();
			        											}
			        										);
			        									},
			        									failure: function(result, request) {
			        										Ext.MessageBox.alert('提示', '操作失败!请刷新后重试.');
			        									}
			        								});
				        						}
				        					}
				        				);
				        			} else {
				        				Ext.MessageBox.alert('提示', '没有任何数据改变');
				        				return false;
				        			}
				        		
				        		}
				        	}
			        	],
			        	bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, centerStore),
					    viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	},
			        	listeners: {
			        		afteredit: function(e) {
			        			var record = e.record;
					       		if (record.get('cudType') == undefined || record.get('cudType') == '') {
					       			record.data['cudType'] = 'U';
					       		}
								record.dirty = true;
								record.modified = e.record;
								if (westStore.modified.indexOf(record) == -1) {
									westStore.modified.push(record);
								}
			        		}
			        	}
					})
	    		],
			    listeners: {
					resize: function(viewport, adjWidth, adjHeight, rawWidth, rawHeight) {
	    				// 当窗体大小改变时，始终保持左侧grid为60%
	    				var westView = Ext.getCmp('westViewport');
	    				if(Ext.isIE) {
	    					westView.setWidth((adjWidth=='auto'?700:adjWidth)*0.6);
	    				} else {
	    					westView.setWidth('60%');
	    				}
					}
				}
	    	});

			function dictTypeController(cudType, title, record) {
	    		var formPanel = new Ext.form.FormPanel({
		            id: 'dictTypeForm',
		            region: 'center',
		            autoScroll: true,
		            layout: 'form',
		            labelWidth: 70,
		            autoWidth: true,
		            labelAlign: 'right',
		            bodyStyle: 'padding:5px 5px 0',
		            border: true,
		            frame: true,
		            fileUpload: true,
		            buttonAlign: 'center',
		            defaults: {
			            anchor: '90%'
				    },
		            items:[
		            	new Ext.form.Hidden({
		            		itemId: 'id',
			            	name: 'dictType.id'
			            }),
			            new Ext.form.TextField({
			            	itemId: 'dictName',
			            	name: 'dictType.dictName',
			            	fieldLabel: cf_getRequiredItem('名称'),
			            	maxLength: 20,
			            	maxLengthText: '名称长度不可大于{0}字符',
			            	allowBlank: false
			            }),
			            new Ext.form.TextField({
			            	itemId: 'dictCode',
			            	name: 'dictType.dictCode',
			            	fieldLabel: cf_getRequiredItem('代码'),
			            	maxLength: 10,
			            	maxLengthText: '代码长度不可大于{0}字符',
			            	emptyText: '建议以简短数字作为代码',
			            	allowBlank: false
			            }),
			            new Ext.form.RadioGroup({
			            	itemId: 'enableStatus',
			            	fieldLabel: '启用状态',
			            	columns: [50, 50],
			            	items: [
			            		{boxLabel: '启用', inputValue: 1, name: 'dictType.enableStatus', checked: true},
			            		{boxLabel: '禁用', inputValue: 0, name: 'dictType.enableStatus'}
			            	]
			            }),
			            new Ext.form.TextArea({
			            	itemId: 'remark',
			            	name: 'dictType.remark',
			            	fieldLabel: '备注'
			            })
		            ],
		            buttons: [{
		                text: '保存',
		                handler: function() {
		                    if(!(formPanel.form.isValid())) {
		                    	return false;
		                    } else {
		                    	formPanel.getForm().submit({
									url: 'DictAction!dictTypeController.do',
									method: 'POST',
									submitEmptyText: false,
									params: {
										'dictType.cudType': cudType
									},
									success: function (result, request) {
										win.hide('dictManager', function() {// 淡入窗口
											refresh('west');// 刷新
						                	win.close();// 关闭
						                }, true);
									},
									failure: function (result, request) {
										Ext.MessageBox.alert('提示', '操作失败!');
						            }
								});
		                    }
		                }
		            },{
		                text: '取消',
		                handler: function() {
		                    win.hide('dictManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
		                }
		            }]
		        });
	    		
	    		win = new Ext.Window({
		            title: title,
		            layout: 'border',
		            width: 350,
		            height: 235,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: formPanel,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					listeners: {
		        		show: function(win) {
		        			if (record) {
								formPanel.getForm().loadRecord(record);
							}
		        		}
		            }
		        });
		        win.show('dictManager');// 淡出窗口
		        
	    	}

			function refresh(type) {
				if(type == 'west') {
					westStore.modified = [];
		           	westStore.removeAll();
		  			westStore.reload();
				} else {
					centerStore.modified = [];
		           	centerStore.removeAll();
		  			centerStore.reload();
				}
	    	}

    	});
    	
    </script>
  </head>
  
  <body>
    <div id="dictManager"></div>
  </body>
</html>